/*
 * @Date: 2024-04-03 14:09:40
 * @LastEditors: bingkui.wu 
 * @LastEditTime: 2024-04-03 20:16:09
 * @Description: 登录事件处理。用于页面监听登录状态变化
 */
import { getUserStroageInfo } from "../services/storage";

let isLogin = false;

const loginCallbacks = [];

/**
 * 添加用户状态改变的事件
 * @param {Function} callback 回调函数
 * @param {Boolean} immediately 是否立即执行，true：立刻执行callback方法
 */
const addLoginListenter = (callback, immediately = false) => {
    loginCallbacks.push(callback);
    if(immediately){
        getUserStroageInfo().then(userInfo => {
            callback(userInfo);
        })
    }
}

const removeLoginListenter = (callback) => {
    const idx = loginCallbacks.indexOf(m => m === callback);
    if(idx >= 0) {
        loginCallbacks.splice(idx, 1);
    }
}

const dispatchLoginEvent = (userInfo) => {
    isLogin = !!userInfo;
    loginCallbacks.forEach(callback => callback(userInfo));
}

export default {
    isLogin,
    addLoginListenter,
    removeLoginListenter,
    dispatchLoginEvent
}